package com.heima.app.gateway.filter;

import io.jsonwebtoken.Claims;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class AuthFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1. 获取request和response对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //1.1 获取用户请求的地址 判断是否是登录如果是则放行
        String path = request.getURI().getPath();
        if(path.contains("login_auth")){
            return chain.filter(exchange);
        }

        //2. 从requesst中获取token
        String token = request.getHeaders().getFirst("token");

        //3. 判断token是否为空如果为空则返回401
        if(StringUtils.isEmpty(token)){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        //4. 如果不为空则校验token是否合法如果合法则放行 如不合法则返回401
        try {
            Claims claimsBody = AppJwtUtil.getClaimsBody(token);
            int status = AppJwtUtil.verifyToken(claimsBody);
            if(1 == status || 2 == status){
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }else {
                return chain.filter(exchange);
            }
        } catch (Exception e) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
    }

    /**
     * 值越小 优先级越高
     * @return
     */
    @Override
    public int getOrder() {
        return -1;
    }
}
